package com.repro.lib_base.bases.fragment

import android.view.LayoutInflater
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.viewbinding.ViewBinding
import com.repro.lib_base.utils.FindClassUtils
import java.lang.reflect.ParameterizedType

/**
 * 抽象创建ViewModel
 */
abstract class BaseVMFragment<M : ViewModel?, VB : ViewBinding> : FinalStateFragment() {
    protected var viewModel: M? = null
    protected var binding: VB? = null
    override fun onFragmentCreateStart(): View? {
        super.onFragmentCreateStart()
        //创建viewModel
        viewModel = getViewModel(FindClassUtils.findNeedType(this.javaClass) as Class<out M?>)
        observeLiveData()
        binding = getViewBindingForFragment(layoutInflater)
        rooView = binding?.root
        return rooView
    }

    @Suppress("UNCHECKED_CAST")
    private fun getViewBindingForFragment(layoutInflater: LayoutInflater): VB {
        val type = javaClass.genericSuperclass as ParameterizedType
        val aClass = type.actualTypeArguments[0] as Class<*>
        val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        return method.invoke(null, layoutInflater) as VB
    }

    /**
     * observeLiveData在这边创建
     */
    protected abstract fun observeLiveData()

    @Override
    override fun <T : ViewModel> getViewModel(mClass: Class<T>): T {
        return super.getViewModel(mClass)
    }
}